BEGIN TRANSACTION;  -- 启动事务‌:ml-citation{ref="1,3" data="citationList"}
BEGIN TRY
    -- 1. 插入订单主表
    INSERT INTO Orders (OrderID, CustomerID, Amount, Status) 
    VALUES (@OrderID, @CustomerID, @Amount, 'Pending');

    -- 2. 扣减库存（使用UPDLOCK锁定库存行）
    UPDATE Products WITH (UPDLOCK)
    SET Stock = Stock - @Quantity
    WHERE ProductID = @ProductID AND Stock >= @Quantity;  -- 检查库存‌:ml-citation{ref="2,7" data="citationList"}

    -- 3. 插入订单明细
    INSERT INTO OrderDetails (OrderID, ProductID, Quantity)
    VALUES (@OrderID, @ProductID, @Quantity);

    -- 4. 提交事务
    COMMIT TRANSACTION;  -- 所有操作成功则提交‌:ml-citation{ref="1,4" data="citationList"}
END TRY
BEGIN CATCH
    -- 回滚事务并记录错误日志
    IF XACT_STATE() = -1 ROLLBACK TRANSACTION;  -- 强制回滚‌:ml-citation{ref="3,4" data="citationList"}
    INSERT INTO ErrorLog (Message, ErrorTime)
    VALUES (ERROR_MESSAGE(), GETDATE());
    THROW;  -- 抛出异常‌:ml-citation{ref="4,6" data="citationList"}
END CATCH;
